import axios from "axios";
import {Message, MessageBox} from "element-ui";
import {getToken} from "@/utils/auth";
import store from "@/store";
import {tansParams} from "@/utils/dou";

// 是否显示重新登录
let isRelogin = {show: false}

const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: process.env.VUE_APP_BASE_URL,
    // 超时
    timeout: 10000
})

// request拦截器
service.interceptors.request.use(config => {
    const notToken = (config.headers || {}).notToken === true;
    if (getToken() && !notToken) {
        config.headers['Authorization'] = getToken();// 让每个请求携带自定义token
    }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
        let url = config.url + '?' + tansParams(config.params);
        url = url.slice(0, -1);
        config.params = {};
        config.url = url;
    }
    return config;
}, error => {
    Message({
        message: error,
        type: 'error',
        duration: 5 * 1000,
    })
    return Promise.reject(error);
})

// 响应拦截器
service.interceptors.response.use(response => {
    const code = response.data.code;
    const msg = response.data.message;
    if (code === 401) {
        if (!isRelogin.show) {
            isRelogin.show = true;
            MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示',{
                confirmButtonText: '重新登陆',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                isRelogin.show = false;
                store.dispatch('Logout').then(() => {
                    location.href = '/admin/login'
                })
            }).catch(() => {
                isRelogin.show = false;
            })
        }
        return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    } else if (code === 500) {
        Message({message: msg, type: 'error'})
        return Promise.reject(new Error(msg))
    } else if (code === 601) {
        Message({message: msg, type: 'warning'})
        return Promise.reject('error')
    } else if (code !== 200) {
        Notification.error({title: msg})
        return Promise.reject('error')
    } else {
        return response.data;
    }
}, error => {
    let {message} = error;
    if (message == "Network Error") {
        message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
        message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
        message: message,
        type: 'error',
        duration: 5 * 1000,
    })
    return Promise.reject(error);
})

export default service
